<?php
// +----------------------------------------------------------------------
// | 有小象汇 自研正版源码 赋能开发者
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 http://www.uxphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 有小象汇并不是自由软件，未经许可不能去掉有小象汇相关版权
// +----------------------------------------------------------------------
// | Author:  有小象汇
// +----------------------------------------------------------------------

namespace app\services\car;


use app\dao\car\CarCategoryDao;
use app\model\car\BasePlace;
use app\model\car\CarCategory;
use app\model\car\CarType;
use app\services\BaseServices;
use crmeb\exceptions\AdminException;
use crmeb\services\FormBuilder as Form;
use think\facade\Route as Url;

/**
 * Class CarCategoryServices
 * @package app\services\shendeng
 */
class CarCategoryServices extends BaseServices
{
    public function __construct(CarCategoryDao $dao)
    {
        $this->dao = $dao;
    }
    /**
     * 列表
     * @param array $where
     * @param string $field
     * @param bool $is_page
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(array $where = [],string $field = '*',bool $is_page = false){
        $page = $limit = 0;
        if($is_page){
            [$page, $limit] = $this->getPageValue();
        }
        $list = $this->dao->getList($where,$field,$page,$limit);
        $count = $this->dao->count($where);
        return compact('list','count');
    }

    /**
     * 获取列表
     * @param array $where
     * @param string $field
     * @param bool $is_page
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCategoryList(array $where = [],string $field = '*',bool $is_page = false){
        $page = $limit = 0;
        if($is_page){
            [$page, $limit] = $this->getPageValue();
        }
        $list = $this->dao->getList($where,$field,$page,$limit);
        $category = array();
        foreach ($list as $key => $item){
            $category[$key]['value'] = $item['id'];
            $category[$key]['label'] = $item['cate_name'];
        }
        $count = $this->dao->count($where);
        return compact('category','count');
    }

    /**
     * 添加/修改
     * @param int $id
     * @return array
     * @throws \FormBuilder\Exception\FormBuilderException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add(int $id){
        $category = $this->dao->get($id);
        $field = array();
        $title = $id ? '修改' : '添加';
        $field[] = Form::hidden('id', $id);
        $field[] = Form::input('cate_name', '分类名称', $category['cate_name']??'');
        $field[] = Form::textarea('cate_desc','分类描述',$category['cate_desc']??'');
        $field[] = Form::radio('status','是否显示',$category['status']??1)->options([['label'=>'显示','value'=>1],['label'=>'隐藏','value'=>0]]);
        $field[] = Form::number('sort', '排序', $category['sort']??'');
        return create_form($title, $field, Url::buildUrl('/car/category/save'), 'POST');
    }

    /**
     * 添加/修改保存
     * @param int $id
     * @param array $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save(int $id, array $data){
        $category = $this->dao->getOne(['cate_name' => $data['cate_name'],'is_del'=>0]);
        if ($id) {
            if (!$this->dao->get($id)) throw new AdminException('数据不存在');
            if ($category && $id != $category['id']) throw new AdminException('该分类已经存在');
            if ($this->dao->update($id, $data)) {
                return true;
            } else {
                throw new AdminException('修改失败或者您没有修改什么');
            }
        } else {
            unset($data['id']);
            if ($category) throw new AdminException('该分类已经存在');
            $data['add_time'] = time();
            if ($this->dao->save($data)) {
                return true;
            } else {
                throw new AdminException('添加失败');
            }
        }
    }

    /**
     * 删除
     * @param int $id
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delCategory(int $id){
        $category = $this->dao->get($id);
        $this->check($category,"category");
        if ($category) {
            $data['is_del'] = 1;
            $data['delete_time'] = time();
            if (!$this->dao->update($id,$data)) {
                throw new AdminException('删除失败,请稍候再试!');
            }
        }
        return '删除成功!';
    }

    /**
     * 显示/隐藏
     * @param int $id
     * @param int $status
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setShow(int $id, int $status){
        $city = $this->dao->getOne(['id' => $id,'is_del'=>0]);
        if (!$city){
            throw new AdminException('数据不存在');
        }
        if ($this->dao->update($id, ['status' => $status])) {
            return $status == 1 ? '显示成功' : '隐藏成功';
        } else {
            throw new AdminException($status == 1 ? '显示失败' : '隐藏失败');
        }
    }

    /**
     * 获取车型分类
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAllCategory($city_id,array $data = []){
        $long_km = get_distance($data['take_latitude'],$data['take_longitude'],$data['return_latitude'],$data['return_longitude'],2);
        $place = BasePlace::alias('p')
//            ->join('base_send_fee f','p.id=f.store_id','left')
            ->where(['p.id'=>$city_id,'p.is_del'=>0,'p.status'=>1,'p.place_type'=>0])
//            ->where('f.mink_km','<=',$long_km)->where('f.max_km','>',$long_km)
            ->column('p.id');
//        if($place) $place_id = join(',',$place);
        $place_id = $city_id;
        $category = CarCategory::field('id,cate_name')->where(['is_del'=>0,'status'=>1])->order('sort desc')->select()->toArray();
        array_unshift($category,['id'=>'','cate_name'=>'全部']);
        foreach ($category as &$item){
            if($place){
                if($item['id'] !== ''){
                    $price = CarType::alias('t')->join('car_type_info i','i.id=t.type_info_id','left')
                        ->where(['i.cate_id'=>$item['id'],'t.is_del'=>0,'t.status'=>1])->where('place_id','in',$place_id)
                        ->limit(1)->order('t.price asc')->value('t.price');//value('t.price');
                    if(is_null($price)){
                        $item['price'] = '暂无';
                    }else{
                        $item['price'] = $price;
                    }
                }else{
                    $check =  CarType::where('is_del','=',0)->where('place_id','in',$place_id)->limit(1)->order('price asc')->value('price');
                    $item['price'] = '暂无';
                    if($check)$item['price'] = $check;
                }
            }else{
                $item['price'] = '暂无';
            }
        }
        foreach($category as $kk=>$vv){
            if($vv['price']=='暂无'){
                unset($category[$kk]);
            }
        }
        $category = array_values($category);
        return $category;
    }
}
